package com.irdstudio.efp.nls.service.impl;


import com.irdstudio.basic.framework.core.constant.SDicToExternalConstant;
import com.irdstudio.basic.framework.core.exception.BizException;
import com.irdstudio.basic.framework.core.util.DateUtility;
import com.irdstudio.basic.framework.core.util.StringUtil;
import com.irdstudio.basic.framework.core.util.TraceUtil;
import com.irdstudio.basic.framework.core.util.sdic.SDicToExternal;
import com.irdstudio.efp.console.service.facade.PrdSoltRuleService;
import com.irdstudio.efp.console.service.facade.PubSysInfoService;
import com.irdstudio.efp.console.service.vo.PrdSoltRuleVO;
import com.irdstudio.efp.cus.service.facade.GreyBlackListService;
import com.irdstudio.efp.cus.service.vo.GreyBlackListVO;
import com.irdstudio.efp.esb.common.constant.EsbBizEnums;
import com.irdstudio.efp.esb.service.bo.req.hlw.ReqAlarmJudgementBean;
import com.irdstudio.efp.esb.service.bo.resp.hlw.RespAlarmJudgementBean;
import com.irdstudio.efp.esb.service.facade.hlw.AlarmJudgementService;
import com.irdstudio.efp.nls.common.constant.PrdAdaptedSoltEnums;
import com.irdstudio.efp.nls.service.facade.NlsQueueSoltComnService;
import com.irdstudio.efp.nls.service.facade.queue.NlsProcessRuleService;
import com.irdstudio.efp.nls.service.vo.queue.NlsProcessRuleVO;
import com.irdstudio.efp.rule.service.vo.RespRuleVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.net.InetAddress;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 需求编号：【2019D0519】（业务提的需求编号）
 * 问题编号：【xxxxxxx】（若不是因为修复问题而新增该类，则留空）
 * 开发人员：qiuyf
 * 创建日期：2019年5月28日 下午2:55:27
 * 功能描述：队列插槽公共处理服务实现类
 */
@Service("nlsQueueSoltComnService")
public class NlsQueueSoltComnServiceImpl implements NlsQueueSoltComnService {
	
	private static final Logger logger = LoggerFactory.getLogger(NlsQueueSoltComnServiceImpl.class);

	@Override
	public void ruleResultDeal(List<RespRuleVO> list, String serno, String prdId, String slotCode) throws Exception {
		// 规则结果信息 
		StringBuilder sb = new StringBuilder();
		boolean flag = true;
		NlsProcessRuleVO nlsProcessRuleVO = new NlsProcessRuleVO();
		nlsProcessRuleVO.setApplySeq(serno);
		nlsProcessRuleVO = nlsProcessRuleService.queryByPk(nlsProcessRuleVO);
		if(Objects.isNull(nlsProcessRuleVO)) {
			logger.error("***************** 根据授信申请流水号【" + serno + "】，获取到的网贷规则过程表信息为空，再次初始化 start***************************");
			flag = false;
			nlsProcessRuleVO = new NlsProcessRuleVO();
			nlsProcessRuleVO.setApplySeq(serno);
			nlsProcessRuleVO.setCusId(nlsProcessRuleVO.getCusId());
			nlsProcessRuleVO.setCusName(nlsProcessRuleVO.getCusName());
			nlsProcessRuleVO.setPrdCode(prdId);
			nlsProcessRuleVO.setPrdName(nlsProcessRuleVO.getPrdName());
			nlsProcessRuleVO.setCreateTime(DateUtility.getCurrDateTime());
			nlsProcessRuleVO.setLastModifyTime(DateUtility.getCurrDateTime());
		}
		List<PrdSoltRuleVO> prdSoltRules = prdSoltRuleService.queryByPrdIdAndSoltCode(prdId, slotCode);
		/**规则结果分组**/
		Map<String, List<RespRuleVO>> map = list.stream().collect(Collectors.groupingBy(RespRuleVO::getRuleId));
		for (int j = 0; j < prdSoltRules.size(); j++) {
			String order = prdSoltRules.get(j).getRuleOrder();
			/** 规则名称method映射 */
			Method methodRuleName = NlsProcessRuleVO.class.getMethod("setRuleName" + order, String.class);
			/** 规则状态method映射 */
			Method methodRuleState = NlsProcessRuleVO.class.getMethod("setRuleState" + order, String.class);
			/** 规则时间method映射 */
			Method methodRuleTime = NlsProcessRuleVO.class.getMethod("setRuleTime" + order, String.class);

			methodRuleName.invoke(nlsProcessRuleVO, prdSoltRules.get(j).getRuleCode());
			methodRuleTime.invoke(nlsProcessRuleVO, DateUtility.getCurrAppDateTimeString());
			if (map.get(prdSoltRules.get(j).getRuleCode()) != null) {
				methodRuleState.invoke(nlsProcessRuleVO, PrdAdaptedSoltEnums.SoltProcessStateEnum.FAILURE.getCode());
				sb.append(prdSoltRules.get(j).getRuleName()).append("规则不通过;");
			} else {
				methodRuleState.invoke(nlsProcessRuleVO, PrdAdaptedSoltEnums.SoltProcessStateEnum.SUCCESS.getCode());
			}
		}
		// 处理网贷规则过程表 
		if(flag) {
			nlsProcessRuleService.updateByPk(nlsProcessRuleVO);
		}else {
			nlsProcessRuleService.insertNlsProcessRule(nlsProcessRuleVO);
		}
		
		if (!list.isEmpty()) {
			throw new BizException(sb.toString());
		}
	}
		@Override
	public void alarmNotice(String objectName, String alramLvl, String message) {
		TraceUtil.clear();
		try {
			ReqAlarmJudgementBean reqAlarmJudgementBean = new ReqAlarmJudgementBean();
			reqAlarmJudgementBean.setMonObjNm(objectName);
			reqAlarmJudgementBean.setMonObjSpfTpVal(objectName);
			reqAlarmJudgementBean.setMonObjLctr(InetAddress.getLocalHost().getHostAddress());
			reqAlarmJudgementBean.setAlrmInf(message);
			reqAlarmJudgementBean.setAlrmTmstmp(DateUtility.getCurrAppDateTimeString());
			// 告警级别为“严重 3”
			reqAlarmJudgementBean.setMonAlrmLvl(alramLvl);
			// 网贷系统接口规定赋值 OCM
			reqAlarmJudgementBean.setAlrmCd("OCM");
			reqAlarmJudgementBean.setAlrmIpAddr(InetAddress.getLocalHost().getHostAddress());
			reqAlarmJudgementBean.setAlrmHstNm(InetAddress.getLocalHost().getHostName());
			RespAlarmJudgementBean respAlarmJudgementBean = alarmJudgementService.alarmJudgement(reqAlarmJudgementBean);
			logger.info("调用告警判断返回码：【" + respAlarmJudgementBean.getRetCd() + "】，返回信息：【" + respAlarmJudgementBean.getRetMsg() + "】");
			if (Objects.nonNull(respAlarmJudgementBean) && EsbBizEnums.AlarmJudgeRespCode.SUCCESS.getValue().equals(respAlarmJudgementBean.getRetCd())) {
				logger.info("调用互金告警接口【60120002_01】成功！返回信息码：" + respAlarmJudgementBean.getRetCd());
			} else {
				logger.error("调用互金告警接口告警【60120002_01】失败！返回信息码：" + respAlarmJudgementBean.getRetCd());
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("调用互金告警接口【60120002_01】异常，异常信息为：", e);
		}

	}
	
	@Override
	public boolean isGreyBlackList(String certType, String certCode) throws BizException {
		boolean isGreyBlackList = false;
		try {
			certType = SDicToExternal.getExternalSysDicVal(SDicToExternalConstant.SYSID_OCM, SDicToExternalConstant.CERT_TYPE, certType);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("校验反洗钱名单，进行证件类型字典项转换时出现异常，异常信息为：", e);
		}
		GreyBlackListVO greyBlackListVO = new GreyBlackListVO();
		greyBlackListVO.setCardType(certType);
		greyBlackListVO.setCardNo(certCode);
		int numGbList = greyBlackListService.countGreyBlkLtByCust(greyBlackListVO);
		if(numGbList > 0) {
			isGreyBlackList = true;
		}
		return isGreyBlackList;
	}
	@Override
	public String getPubSysOpenDay(String sysId) {
		//查询营业日期
		String openday = pubSysInfoService.getOpenday(sysId);
		String isOpenday = Optional.ofNullable(openday).orElse("");
		if(StringUtil.isNullorBank(isOpenday)) {
			logger.error("通过系统ID【" + sysId + "】，查询到的营业日期为空！");
		}
		return isOpenday;
	}
	
	@Autowired
	@Qualifier("prdSoltRuleService")
	private PrdSoltRuleService prdSoltRuleService;
	
	@Autowired
	@Qualifier("nlsProcessRuleService")
	private NlsProcessRuleService nlsProcessRuleService;

	@Autowired
	@Qualifier("alarmJudgementService")
	private AlarmJudgementService alarmJudgementService;

	@Autowired
	@Qualifier("greyBlackListService")
	private GreyBlackListService greyBlackListService;
	@Autowired
	@Qualifier("pubSysInfoService")
	private PubSysInfoService pubSysInfoService;

}
